package com.example.library.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.library.entity.User;
import com.example.library.mapper.UserMapper;
import com.example.library.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sx
 * @since 2024-12-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SecurityContext securityContext;

    @Override
    public User findByName(String name){
        return this.getOne(new QueryWrapper<User>().eq("name",name));
    }

    @Override
    public User Userlogin(String name, String password){
        User user = userMapper.findByUserName(name);
        if(user != null &&  user.getPassword().equals(password)){
            return user;
        }
        return null;
    }

    @Override
    public User getCurrentUser() {
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof User) {
            return (User) authentication.getPrincipal();
        }
        return null;
    }

    @Override
    public User updateProfile(User user) {
        User currentUser = getCurrentUser();
        if (currentUser != null) {
            // 更新当前登录管理员的信息
            currentUser.setName(user.getName());
            currentUser.setEmail(user.getEmail());
            userMapper.updateById(currentUser);
            return currentUser;
        }
        return null;
    }
}
